import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String message;
}
@WebServlet("/message")
public class messageWall extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    // 用表收集多个message对象
    private List<Message> messageList = new ArrayList<>();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 通过这个方法来处理提交的信息
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        messageList.add(message);
        System.out.println("消息提交成功 ! message = " + message);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 这个方法是浏览器向服务器请求页面时，获取到之前所有的 “留言消息”
        // 需要返回一个json字符串数组，jackson会自动帮我们处理好格式
        String respString = objectMapper.writeValueAsString(messageList);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respString);

    }
}
